package com.wepa.smackgcp.oauth2;

import java.io.IOException;

import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.sasl.SASLMechanism;
import org.jivesoftware.smack.util.Base64;

public class GoogleOAuth2SASLMechanism extends SASLMechanism {

    private static final String NAME        = "X-OAUTH2";
    private static final String AUTH_STANZA = "<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" "
	                                            + "mechanism=\"X-OAUTH2\" auth:service=\"oauth2\" "
	                                            + "xmlns:auth=\"http://www.google.com/talk/protocol/auth\">"
	                                            + "%s</auth>";

    public GoogleOAuth2SASLMechanism(SASLAuthentication saslAuthentication) {
	super(saslAuthentication);
    }

    @Override
    protected String getName() {
	return NAME;
    }

    @Override
    protected void authenticate() throws IOException, XMPPException {

	// combine the google id and OAuth2 access token (password) into an encoded string
	byte credentialBytes[] = ("\0" + authenticationId + "\0" + password).getBytes("UTF-8");
	String authenticationText = Base64.encodeBytes(credentialBytes, Base64.DONT_BREAK_LINES);

	// insert the credentials data into the main auth stanza
	final String completeAuthStanza = String.format(AUTH_STANZA, authenticationText);

	// create and send a packet that will use the completed OAuth2 stanza for authentication
	Packet p = new Packet() {
	    @Override
	    public String toXML() {
		return completeAuthStanza;
	    }
	};
	getSASLAuthentication().send(p);
    }
}